﻿using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Faser_Shop.Utils;

namespace Faser_Shop.Filters
{
    //全局异常过滤器
    public class GlobalExceptionFilter : IExceptionFilter
    {
        private readonly ILogger<GlobalExceptionFilter> _logger;
        public GlobalExceptionFilter(ILogger<GlobalExceptionFilter> logger)
        {
            _logger = logger;
        }

        public void OnException(ExceptionContext context)
        {
            var operation = context.HttpContext.Request.RouteValues["controller"] + "/" + context.HttpContext.Request.RouteValues["action"];

            _logger.LogError(context.Exception, $"<Exception> [{operation}] " + context.Exception.Message); //记录错误日志
                                                                                                           //拦截处理
            if (!context.ExceptionHandled)
            {
                context.Result = new ObjectResult(ApiResult.ServerInternalError(context.Exception.Message));
                context.ExceptionHandled = true;
            }
        }
    }
}
